import configparser  # 新增配置解析器
import re
import os
import shutil
import sys
import subprocess
import configparser

def read_config():
    """读取多项目配置文件"""
    exe_dir = os.path.dirname(sys.executable)
    config_path = os.path.join(exe_dir, "VersionManageConfig.txt")
    config = configparser.ConfigParser()

    try:
        # 保留旧版单项目配置兼容性
        if not os.path.exists(config_path):
            raise FileNotFoundError("❌ 配置文件不存在")

        config.read(config_path, encoding='utf-8')

        # 验证必须包含至少一个项目
        if not config.sections():
            raise ValueError("❌ 配置文件中未定义任何项目（如 [Project1]）")

        return config

    except Exception as e:
        raise RuntimeError(f"❌ 配置文件解析失败: {str(e)}")


def process_project(project_name, project_config):
    """处理单个项目的文件复制逻辑"""

    build_keys = ['keil_project', 'keil_compiler_path']
    missing_keys = [key for key in build_keys if key not in project_config]
    if missing_keys:
        print(f"❌ 项目 [{project_name}] 缺失编译配置项: {', '.join(missing_keys)}")
    keil_compiler_path = project_config['keil_compiler_path'].replace('\\', '/')
    keil_project = project_config['keil_project'].replace('\\', '/')

    build_cmd = [r".\Keil-Autopiler.exe", keil_compiler_path, keil_project]

    print(f"编译配置项:", build_cmd)

    result = subprocess.run(build_cmd, capture_output=True, text=True, check=True)
    print(result.stdout)
    if "Copy above file(s) SUCCESS" in result.stdout:
        print(f"项目 [{project_name}] 编译成功")
    else:
        print(f"项目 [{project_name}] 编译失败")

    # 参数提取与校验
    required_keys = ['version_file', 'regex_pattern', 'source_files', 'target_dir']
    missing_keys = [key for key in required_keys if key not in project_config]
    if missing_keys:
        raise KeyError(f"❌ 项目 [{project_name}] 缺失配置项: {', '.join(missing_keys)}")

    # 路径格式化
    version_file = project_config['version_file'].replace('\\', '/')
    regex_pattern = project_config['regex_pattern']
    source_files = [f.strip().replace('\\', '/') for f in project_config['source_files'].split(';')]
    target_dir = project_config['target_dir'].replace('\\', '/')

    # 提取版本号
    with open(version_file, "r", encoding='utf-8') as f:
        content = f.read()
    version_match = re.search(regex_pattern, content)
    if not version_match:
        raise ValueError(f"❌ 项目 [{project_name}] 未匹配到版本号")
    version = version_match.group(1).replace("\"", "")

    # 创建目标目录
    os.makedirs(target_dir, exist_ok=True)

    # 复制所有源文件
    success_count = 0
    for src_path in source_files:
        if not os.path.exists(src_path):
            print(f"⚠️ 项目 [{project_name}] 源文件不存在: {src_path}")
            continue

        base_name = os.path.basename(src_path)
        name_part, ext = os.path.splitext(base_name)
        new_name = f"{name_part}_{version}{ext}"
        dest_path = os.path.join(target_dir, new_name).replace('\\', '/')

        shutil.copy2(src_path, dest_path)
        print(f"✅ 项目 [{project_name}] 已复制: {base_name} → {new_name}")
        success_count += 1

    return success_count, len(source_files)


def copy_versions():
    """多项目批量处理入口"""
    config = read_config()
    total_success = 0
    total_files = 0

    for project_name in config.sections():
        print(f"\n🔨 开始处理项目: [{project_name}]")
        try:
            success, total = process_project(project_name, config[project_name])
            total_success += success
            total_files += total
            print(f"📊 项目 [{project_name}] 完成: {success}/{total} 文件")
        except Exception as e:
            print(f"❌ 项目 [{project_name}] 处理失败: {str(e)}")

    print(f"\n🌈 所有项目处理完成! 总成功: {total_success}/{total_files} 文件")


def wait_for_exit():
    """等待用户按键后退出"""
    if sys.platform.startswith('win'):
        try:
            import msvcrt
            print("\n⚠️ 按任意键退出...")
            msvcrt.getch()
        except ImportError:
            input("\n⚠️ 按回车键退出...")
    else:
        input("\n⚠️ 按回车键退出...")


if __name__ == '__main__':
    try:
        copy_versions()
        wait_for_exit()
    except Exception as e:
        print(f"\n{str(e)}")
        wait_for_exit()
        sys.exit(1)